package com.andy.wan.android.mvp.net;

import android.util.Log;

import com.andy.wan.android.mvp.api.WanAndroidApi;

import java.util.concurrent.TimeUnit;

import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Author: luofan
 * @CreateDate: 2020/3/17 16:59
 * @Description:
 */
public class RetrofitUtil {

    private static final String TAG = "RetrofitUtil";

    private static final RetrofitUtil ourInstance = new RetrofitUtil();

    public static RetrofitUtil getInstance() {
        return ourInstance;
    }

    private Retrofit mRetrofit;

    private RetrofitUtil() {
        mRetrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .baseUrl(WanAndroidApi.BASE_URL)
                .client(genOkHttpClient())
                .build();

    }

    private OkHttpClient genOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new Logger());
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor)
//                .addInterceptor(new HeaderInterceptor())
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS);
        return builder.build();
    }

    private static class Logger implements HttpLoggingInterceptor.Logger {

        @Override
        public void log(String message) {
            Log.e(TAG, message);
        }
    }

    public <T> T create(final Class<T> service) {
        return mRetrofit.create(service);
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }
}
